#coding:utf-8
'''
create on 2017-04-20

@author:sandy
'''


from pycommon import Const
import User
import GameDb
import logging

class UserManager(object):
    def __init__(self):
        self.usermap = {}
        
    def start(self):
        l = task.LoopingCall(self.onTimer)
        l.start(10, False)
    
    def stop(self):
        pass
    
    def onTimer(self):
        pass

    def getUser(self, uid):
        ret = self.usermap.get(uid,None)
        return ret

    def removeUser(self,uid):
        return self.usermap.pop(uid,None)

    def onUserLogin(self,gatesid,uid,pid,session,cver,partner,nickname = u'', photo = u'',sex = 1):
        nickname = nickname if nickname != u'' else u'玩家'+str(uid)
        photo = photo if photo != u'' else u'http://wx.qlogo.cn/mmopen/azOicib7sicR7mfakokXHTJVsSHBNG95Cdd13icsKrEt8t5w2Xicia21HcQMbBzYO4vp8Xicq1RIZR0ia2t3wYnXiciaIkaiaOx263Eic19m/0'
        olduser = self.getUser(uid)
        if olduser:
            logging.warn(u"onUserLogin() Old User uid=%d pid=%d",uid,pid)
            if olduser.getGameSid() != 0:
                olduser.kickFromGame(Const.ERR_RELOGIN)
            if olduser.getGateSid() != 0:
                olduser.kickFromGate(Const.ERR_RELOGIN)
        else:
            logging.debug(u"onUserLogin() New User uid=%d pid=%d",uid,pid)
            olduser = User.User(uid,pid,session)
            self.usermap[uid] = olduser
        olduser.setLastActiveTime()
        olduser.changeSession(session)
        olduser.setGateClientPid(pid)
        olduser.setUserBasicInfo(gatesid,cver, partner, nickname, photo , sex)
        GameDb.instance.loadUserInfo(uid)

    def userEnterGame(self, uid, gamesid):
        user = self.usermap.get(uid,None)
        user.setGameSid(gamesid)
        user.setLastActiveTime()

    def userExitGame(self, uid):
        user = self.usermap.get(uid,None)
        if user != None:
            user.setGameSid(0)
            user.setLastActiveTime()
        else:
            logging.debug("userExitGame uid=%d user==None",uid)

    def getOnlineUserCount(self):
        ret = []
        for u in self.usermap.values():
            if 0 != u.getGameSid():
                ret.append(u)
        return len(ret)

    
    def getAllUserBySid(self,sid):
        ret = []
        for u in self.usermap.values():
            if sid == u.getGameSid():
                ret.append(u)
        return ret

    def getAllUser(self):
        userlist = []
        for u in self.usermap.values():
            userlist.append(u)
        return userlist

instance = UserManager()